<template>
  <div class="boss-view">
    <!-- 错误提示 -->
    <el-alert 
      v-if="errorMsg" 
      type="error" 
      :description="errorMsg" 
      show-icon 
      class="mb-4"
      closable
      @close="errorMsg = ''"
    />

    <el-card class="chart-card">
      <!-- 1. 筛选区域 -->
      <div class="filter-wrapper">
        <el-select
          v-model="selectedStoreId"
          placeholder="选择店铺"
          @change="handleStoreChange"
          :disabled="isLoadingStores"
          class="store-select"
        >
          <el-option
            v-for="store in stores"
            :key="store.storeId"
            :label="`${store.storeName} (ID: ${store.storeId})`"
            :value="store.storeId"
          />
        </el-select>
		<el-radio-group v-model="grain" size="small" :disabled="isLoading">
		  <el-radio-button label="daily">每日</el-radio-button>
		  <el-radio-button label="monthly">每月</el-radio-button>
		  <el-radio-button label="yearly">每年</el-radio-button>
		</el-radio-group>

        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :disabled="isLoading || isLoadingStores"
          class="date-picker"
        />

        <el-button
          @click="fetchStatData"
          class="query-btn"
          :loading="isLoading"
          :disabled="!selectedStoreId || !dateRange.length"
          type="primary"
        >
          查询统计数据
        </el-button>
      </div>

      <!-- 2. 统计卡片（移除库存周转率卡片） -->
      <div class="stats-card-wrapper">
        <el-card class="stat-card" :loading="isLoading">
          <div class="stat-card__content">
            <div class="stat-card__icon">
              <el-icon size="24" color="#FF8C00">
                <ShoppingCart />
              </el-icon>
            </div>
            <div class="stat-card__info">
              <div class="stat-card__title">订单总数</div>
              <div class="stat-card__value">{{ rangeStats.orderCount }} 单</div>
            </div>
          </div>
        </el-card>

        <el-card class="stat-card" :loading="isLoading">
          <div class="stat-card__content">
            <div class="stat-card__icon">
              <el-icon size="24" color="#FF8C00">
                <Money />
              </el-icon>
            </div>
            <div class="stat-card__info">
              <div class="stat-card__title">总销售额</div>
              <div class="stat-card__value">¥{{ formatNumber(rangeStats.totalSales) }}</div>
            </div>
          </div>
        </el-card>

        <el-card class="stat-card" :loading="isLoading">
          <div class="stat-card__content">
            <div class="stat-card__icon">
              <el-icon size="24" color="#4CAF50">
                <Timer />
              </el-icon>
            </div>
            <div class="stat-card__info">
              <div class="stat-card__title">高峰时段</div>
              <div class="stat-card__value">{{ peakHour || '暂无数据' }}</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 3. 图表区域（移除库存周转率图表） -->
      <div class="charts-wrapper">
        <!-- 每日订单数量折线图 -->
        <div class="chart-item">
          <el-card shadow="hover">
            <div slot="header" class="chart-header">
              <span>每日订单数量趋势</span>
            </div>
            <div v-if="!dailyOrders.length && !isLoading" class="empty-container">
              <el-empty description="暂无订单数据" />
            </div>
            <div v-else class="chart-container" style="position: relative; z-index: 10;">
              <div id="daily-orders-chart" style="width: 100%; height: 400px;"></div>
            </div>
          </el-card>
        </div>

        <!-- 每日销售额折线图 -->
        <div class="chart-item">
          <el-card shadow="hover" class="mt-4">
            <div slot="header" class="chart-header">
              <span>每日销售额趋势</span>
            </div>
            <div v-if="!dailySales.length && !isLoading" class="empty-container">
              <el-empty description="暂无销售数据" />
            </div>
            <div v-else class="chart-container" style="position: relative; z-index: 10;">
              <div id="daily-sales-chart" style="width: 100%; height: 400px;"></div>
            </div>
          </el-card>
        </div>

        <!-- 高峰期分析图 -->
        <div class="chart-item">
          <el-card shadow="hover" class="mt-4">
            <div slot="header" class="chart-header">
              <span>订单高峰期分析</span>
            </div>
            <div v-if="!hourlyOrders.length && !isLoading" class="empty-container">
              <el-empty description="暂无订单数据" />
            </div>
            <div v-else class="chart-container" style="position: relative; z-index: 10;">
              <div id="peak-hour-chart" style="width: 100%; height: 400px;"></div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 4. 统计区间信息 -->
      <div v-if="rangeStats.startDate" class="range-info">
        统计区间: {{ getSelectedStoreName() }} {{ rangeStats.startDate }} 至 {{ rangeStats.endDate }}
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import { ShoppingCart, Money, Timer } from '@element-plus/icons-vue';
import { ElMessage, ElEmpty, ElIcon } from 'element-plus';

// 响应式状态（移除库存相关变量）
const stores = ref([]);
const selectedStoreId = ref(0);
const isLoadingStores = ref(false);
const dateRange = ref([]);
const rangeStats = ref({
  orderCount: 0,
  totalSales: 0,
  startDate: '',
  endDate: ''
});
const dailyOrders = ref([]);
const dailySales = ref([]);
const hourlyOrders = ref([]);
const peakHour = ref('');
const isLoading = ref(false);
const errorMsg = ref('');
const grain = ref('daily');

// 图表实例（移除库存周转率图表）
let dailyOrdersChart = null;
let dailySalesChart = null;
let peakHourChart = null;

// 接口基础地址
const baseApi = 'http://49.232.154.120:8080';

// 初始化
onMounted(() => {
  initDefaultDateRange();
  fetchStores();
  window.addEventListener('resize', handleWindowResize);
});

// 数据聚合函数
function aggregateByGrain(list, grainType) {
  const map = new Map()
  list.forEach(order => {
    const d = new Date(order.orderlistTime)
    let key
    switch (grainType) {
      case 'daily':
        key = `${d.getFullYear()}-${padZero(d.getMonth() + 1)}-${padZero(d.getDate())}`
        break
      case 'monthly':
        key = `${d.getFullYear()}-${padZero(d.getMonth() + 1)}`
        break
      case 'yearly':
        key = `${d.getFullYear()}`
        break
    }
    const old = map.get(key) || { sales: 0, count: 0 }
    old.sales += Number(order.orderlistPrice || 0)
    old.count += 1
    map.set(key, old)
  })
  const sorted = [...map.entries()].sort((a, b) => a[0].localeCompare(b[0]))
  return {
    labels: sorted.map(i => i[0]),
    sales:  sorted.map(i => parseFloat(i[1].sales.toFixed(2))),
    counts: sorted.map(i => i[1].count)
  }
}

// 分析高峰期数据
function analyzePeakHours(orders) {
  const hourlyMap = new Array(24).fill(0);
  
  orders.forEach(order => {
    const hour = new Date(order.orderlistTime).getHours();
    hourlyMap[hour]++;
  });
  
  const hourlyData = hourlyMap.map((count, hour) => ({
    hour: `${hour}:00`,
    value: count
  }));
  
  let maxCount = 0;
  let peakHourStr = '';
  
  hourlyMap.forEach((count, hour) => {
    if (count > maxCount) {
      maxCount = count;
      peakHourStr = `${hour}:00`;
    } else if (count === maxCount && maxCount > 0) {
      peakHourStr += `, ${hour}:00`;
    }
  });
  
  return {
    hourlyData,
    peakHour: maxCount > 0 ? peakHourStr : '暂无数据'
  };
}

// 日期处理工具函数
const normalizeDate = (date) => {
  const normalized = new Date(date);
  normalized.setHours(0, 0, 0, 0);
  return normalized;
};

const initDefaultDateRange = () => {
  const today = normalizeDate(new Date());
  const sevenDaysAgo = normalizeDate(new Date(today.getTime() - 6 * 24 * 60 * 60 * 1000));
  dateRange.value = [sevenDaysAgo, today];
};

const ensureDateOrder = () => {
  if (!dateRange.value || dateRange.value.length < 2) return null;
  
  const start = normalizeDate(dateRange.value[0]);
  const end = normalizeDate(dateRange.value[1]);
  const today = normalizeDate(new Date());
  
  if (start > end) {
    dateRange.value = [end, start];
    ElMessage.warning('开始日期不能晚于结束日期，已自动调整');
  }
  
  if (end > today) {
    dateRange.value = [start, today];
    ElMessage.warning('结束日期不能晚于今天，已自动调整');
  }
  
  return { start, end };
};

const formatDate = (date) => {
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const formatStartApiTime = (date) => {
  return `${formatDate(date)} 00:00:00`;
};

const formatEndApiTime = (date) => {
  return `${formatDate(date)} 23:59:59`;
};

const padZero = (num) => {
  return num.toString().padStart(2, '0');
};

const formatNumber = (num) => {
  if (isNaN(num) || !isFinite(num)) return '0.00';
  return num.toLocaleString('zh-CN', { 
    minimumFractionDigits: 2, 
    maximumFractionDigits: 2 
  });
};

// 接口请求
const httpRequest = async (url) => {
  try {
    const response = await axios.get(url, {
      headers: { 'Content-Type': 'application/json;charset=UTF-8' },
      timeout: 10000
    });
    
    if (response.status !== 200) {
      throw new Error(`请求失败，状态码: ${response.status}`);
    }
    
    return response.data;
  } catch (error) {
    const errMsg = error.response?.data?.message || error.message || '网络请求异常';
    throw new Error(errMsg);
  }
};

const fetchStores = async () => {
  isLoadingStores.value = true;
  errorMsg.value = '';
  
  try {
    const url = `${baseApi}/store/list`;
    const res = await httpRequest(url);
    
    if (Array.isArray(res) && res.length > 0) {
      stores.value = res;
      if (selectedStoreId.value === 0) {
        selectedStoreId.value = res[0].storeId;
      }
    } else {
      ElMessage.warning('未获取到店铺数据');
    }
  } catch (error) {
    errorMsg.value = `获取店铺失败：${error.message}`;
    ElMessage.error(errorMsg.value);
  } finally {
    isLoadingStores.value = false;
  }
};

// 数据处理
const calculateStats = (orders, start, end) => {
  const agg = aggregateByGrain(orders, grain.value)
  const totalSales = agg.sales.reduce((a, b) => a + b, 0)
  const orderCount = orders.length

  const dailyOrders = agg.labels.map((lab, idx) => ({ date: lab, value: agg.counts[idx] }))
  const dailySales  = agg.labels.map((lab, idx) => ({ date: lab, value: agg.sales[idx]  }))
  
  const { hourlyData, peakHour } = analyzePeakHours(orders);

  return {
    rangeStats: {
      orderCount,
      totalSales,
      startDate: formatDate(start),
      endDate: formatDate(end)
    },
    dailySales,
    dailyOrders,
    hourlyData,
    peakHour
  }
}

// 监听粒度变化
watch(grain, () => {
  if (selectedStoreId.value && dateRange.value.length) fetchStatData()
})

// 创建图表实例
const createChartInstance = (domId) => {
  let oldChart;
  switch(domId) {
    case 'daily-orders-chart':
      oldChart = dailyOrdersChart;
      break;
    case 'daily-sales-chart':
      oldChart = dailySalesChart;
      break;
    case 'peak-hour-chart':
      oldChart = peakHourChart;
      break;
  }
  
  if (oldChart) {
    oldChart.dispose();
  }
  
  return new Promise(resolve => {
    nextTick(() => {
      const dom = document.getElementById(domId);
      if (!dom) {
        console.error(`图表DOM不存在：${domId}，尝试再次获取...`);
        setTimeout(() => {
          const retryDom = document.getElementById(domId);
          if (!retryDom) {
            console.error(`再次尝试获取图表DOM ${domId} 失败`);
            ElMessage.error(`图表加载失败：未找到图表容器`);
            resolve(null);
            return;
          }
          initializeChart(retryDom, domId, resolve);
        }, 300);
        return;
      }
      initializeChart(dom, domId, resolve);
    });
  });
};

// 图表初始化辅助函数
const initializeChart = (dom, domId, resolve) => {
  dom.style.width = '100%';
  dom.style.height = '400px';
  dom.style.display = 'block';
  
  try {
    const chart = echarts.init(dom);
    console.log(`图表实例创建成功：${domId}`);
    resolve(chart);
  } catch (error) {
    console.error(`图表实例创建失败：${domId}`, error);
    ElMessage.error(`图表加载失败：${error.message}`);
    resolve(null);
  }
};

// 渲染普通图表
const renderChart = async (chartId, data, title, yName) => {
  const chart = await createChartInstance(chartId);
  if (!chart || !data.length) return;
  
  const option = {
    title: { text: title, left: 'center' },
    tooltip: { trigger: 'axis' },
    grid: { left: '10%', right: '10%', bottom: '20%', top: '15%', containLabel: true },
    xAxis: {
      type: 'category',
      data: data.map(item => item.date),
      axisLabel: { rotate: 45, interval: 0 }
    },
    yAxis: { type: 'value', name: yName, min: 0 },
    series: [{
      name: yName,
      type: 'line',
      data: data.map(item => item.value),
      lineStyle: { width: 3, color: chartId === 'daily-orders-chart' ? '#FF8C00' : '#6200ee' },
      itemStyle: { radius: 6 }
    }]
  };
  
  try {
    chart.setOption(option);
    chart.resize();
  } catch (error) {
    console.error(`图表渲染失败：${chartId}`, error);
    ElMessage.error(`图表数据加载失败：${error.message}`);
  }
};

// 渲染高峰期分析图
const renderPeakHourChart = async (data) => {
  const chart = await createChartInstance('peak-hour-chart');
  if (!chart || !data.length) return;
  
  const maxValue = Math.max(...data.map(item => item.value));
  const peakColor = data.map(item => item.value === maxValue ? '#FF5252' : '#42A5F5');
  
  const option = {
    title: { text: '订单高峰期分析（按小时）', left: 'center' },
    tooltip: { 
      trigger: 'axis',
      formatter: '{b}: {c} 单'
    },
    grid: { left: '5%', right: '5%', bottom: '10%', top: '15%', containLabel: true },
    xAxis: {
      type: 'category',
      data: data.map(item => item.hour),
      name: '时间段',
      axisLabel: { interval: 0 }
    },
    yAxis: { 
      type: 'value', 
      name: '订单数量', 
      min: 0,
      axisLabel: { formatter: '{value} 单' }
    },
    series: [{
      name: '订单数',
      type: 'bar',
      data: data.map(item => item.value),
      itemStyle: {
        color: function(params) {
          return peakColor[params.dataIndex];
        }
      },
      markPoint: {
        data: [{
          type: 'max',
          name: '峰值',
          itemStyle: { color: '#FF5252' }
        }]
      }
    }]
  };
  
  try {
    chart.setOption(option);
    chart.resize();
  } catch (error) {
    console.error('高峰期图表渲染失败：', error);
    ElMessage.error(`高峰期图表加载失败：${error.message}`);
  }
};

// 窗口resize处理
const handleWindowResize = () => {
  dailyOrdersChart?.resize();
  dailySalesChart?.resize();
  peakHourChart?.resize();
};

// 店铺切换事件
const handleStoreChange = () => {
  if (dateRange.value.length) {
    fetchStatData();
  }
};

// 数据查询（移除库存周转率相关代码）
const fetchStatData = async () => {
  isLoading.value = true;
  errorMsg.value = '';
  dailyOrders.value = [];
  dailySales.value = [];
  hourlyOrders.value = [];
  peakHour.value = '';
  
  try {
    const dateResult = ensureDateOrder();
    if (!dateResult) {
      throw new Error('请选择有效的日期范围');
    }
    const { start, end } = dateResult;
    
    if (!selectedStoreId.value) {
      throw new Error('请先选择店铺');
    }
    
    const storeId = selectedStoreId.value;
    const startTime = formatStartApiTime(start);
    const endTime = formatEndApiTime(end);
    const url = `${baseApi}/orderlist/search?storeId=${storeId}&startTime=${encodeURIComponent(startTime)}&endTime=${encodeURIComponent(endTime)}`;
    
    // 获取订单数据
    const orders = await httpRequest(url);
    console.log("接口返回订单数据：", orders);
    
    if (!orders.length) {
      ElMessage.info('该时间段内无订单数据');
      rangeStats.value = { orderCount: 0, totalSales: 0, startDate: formatDate(start), endDate: formatDate(end) };
      await Promise.all([
        renderChart('daily-orders-chart', [], '每日订单数量趋势', '订单数（单）'),
        renderChart('daily-sales-chart', [], '每日销售额趋势', '销售额（元）'),
        renderPeakHourChart([])
      ]);
      return;
    }
    
    // 处理数据
    const statResult = calculateStats(orders, start, end);
    rangeStats.value = statResult.rangeStats;
    dailyOrders.value = statResult.dailyOrders;
    dailySales.value = statResult.dailySales;
    hourlyOrders.value = statResult.hourlyData;
    peakHour.value = statResult.peakHour;
    
    // 渲染所有图表
    await Promise.all([
      renderChart('daily-orders-chart', dailyOrders.value, '每日订单数量趋势', '订单数（单）'),
      renderChart('daily-sales-chart', dailySales.value, '每日销售额趋势', '销售额（元）'),
      renderPeakHourChart(hourlyOrders.value)
    ]);
    
    ElMessage.success(`查询成功：${rangeStats.value.orderCount}单，¥${formatNumber(rangeStats.value.totalSales)}`);
  } catch (error) {
    errorMsg.value = `查询失败：${error.message}`;
    ElMessage.error(errorMsg.value);
    console.error("查询错误：", error);
  } finally {
    isLoading.value = false;
  }
};

// 辅助函数
const getSelectedStoreName = () => {
  const store = stores.value.find(s => s.storeId === selectedStoreId.value);
  return store?.storeName || '未知店铺';
};

// 清理
watch(
  () => [],
  () => {
    window.removeEventListener('resize', handleWindowResize);
    if (dailyOrdersChart) dailyOrdersChart.dispose();
    if (dailySalesChart) dailySalesChart.dispose();
    if (peakHourChart) peakHourChart.dispose();
  },
  { once: true }
);
</script>

<style scoped>
/* 移除库存相关样式 */
.chart-container {
  width: 100%;
  height: 400px;
  padding: 10px;
  box-sizing: border-box;
  position: relative;
  z-index: 10;
}

.boss-view {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.chart-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.filter-wrapper {
  margin-bottom: 20px;
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.store-select {
  width: 280px;
}

.date-picker {
  width: 380px;
}

.query-btn {
  flex-shrink: 0;
}

.stats-card-wrapper {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 280px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.stat-card__content {
  display: flex;
  align-items: center;
  padding: 16px;
}

.stat-card__icon {
  margin-right: 16px;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: rgba(255, 140, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-card__title {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-card__value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.charts-wrapper {
  width: 100%;
}

.chart-item {
  width: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-container {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.range-info {
  margin-top: 20px;
  color: #666;
  font-size: 14px;
  text-align: center;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

@media (max-width: 768px) {
  .store-select, .date-picker {
    width: 100%;
  }
  
  .stats-card-wrapper {
    flex-direction: column;
  }
}
</style>
    